<template>
	<Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
		<el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120px">
			<el-form-item label="所属社区" prop="commId">
				<el-tree-select v-model="formData.commId" :data="communityTree" :props="defaultProps" check-strictly default-expand-all placeholder="请选择所属社区" value-key="id" />
			</el-form-item>
			<el-form-item label="所属厂家" prop="factoryCode">
				<el-select v-model="formData.factoryCode" @change="getTypeCodes">
					<el-option v-for="dict in getStrDictOptions(DICT_TYPE.METER_FACTORY)" :key="dict.value" :label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="设备类型" prop="typeCode" v-if="formData.factoryCode == '1'">
				<el-select v-model="formData.typeCode" @change="getHxnyProducts">
					<el-option v-for="dict in typeCodes" :key="dict.value" :label="dict.label" :value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="设备型号" prop="productId" v-if="formData.factoryCode == '1'">
				<el-select v-model="formData.productId">
					<el-option v-for="p in products" :key="p.id" :label="p.name" :value="p.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="安装地址" prop="serialServerName">
				<el-input v-model="formData.serialServerName" placeholder="请输入集中器名称" />
			</el-form-item>
			<el-form-item label="设备编码" prop="serialServerNo">
				<el-input v-model="formData.serialServerNo" placeholder="请输入集中器编码" />
			</el-form-item>
			<el-form-item label="安装人员" prop="installMemberId">
				<el-input v-model="formData.installMemberName" :readonly="true">
					<template #append>
						<el-button @click="openSelectMember">选择</el-button>
						<el-button @click="clearSelectMember">清空</el-button>
					</template>
				</el-input>
			</el-form-item>
			<el-row>
				<el-col :span="12">
					<el-form-item label="使用状态" prop="useStatus">
						<el-select v-model="formData.useStatus">
							<el-option v-for="dict in getStrDictOptions(DICT_TYPE.METER_SERIAL_SERVER_USE_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="排序" prop="sort">
						<el-input v-model="formData.sort" placeholder="请输入排序" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="安装地址">
				<el-input v-model="formData.houseIdName" :readonly="true">
					<template #append>
						<el-button @click="openSelectHouse">选择</el-button>
						<el-button @click="clearSelectHouse">清空</el-button>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="电表系统ID" prop="externalLinkId">
				<el-input v-model="formData.externalLinkId" :readonly="true" style="width: 50%" />
				<span style="margin-left: 5px; color: green">与电表系统同步后返回的ID</span>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button type="primary" @click="submitForm">确 定</el-button>
			<el-button @click="dialogVisible = false">取 消</el-button>
		</template>
	</Dialog>

	<MemberUserSelect ref="openSelectMemberRef" @confirm-member-user="confirmMemberUser" />
	<BuildingAddressSelect ref="openSelectHouseRef" @confirm-building-address="confirmBuildingAddress" />
</template>
<script lang="ts" setup>
	import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
	import { defaultProps, handleTree } from '@/utils/tree'
	import * as MeterSerialServerApi from '@/api/zwsj/meterSerialServer'
	import { MeterHxnyDictApi } from '@/api/zwsj/meterhxnydict'
	import * as CommunityApi from '@/api/zwsj/community'
	import MemberUserSelect from '@/views/zwsj/common/MemberUserSelect.vue'
	import BuildingAddressSelect from '@/views/zwsj/common/BuildingAddressSelect.vue'

	defineOptions({ name: 'MeterSerialServerForm' })

	const { t } = useI18n() // 国际化
	const message = useMessage() // 消息弹窗

	const dialogVisible = ref(false) // 弹窗的是否展示
	const dialogTitle = ref('') // 弹窗的标题
	const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
	const formType = ref('') // 表单的类型：create - 新增；update - 修改
	const formData = ref({
		id: undefined,
		factoryCode: undefined,
		typeCode: undefined,
		productId: undefined,
		commId: undefined,
		serialServerName: undefined,
		serialServerNo: undefined,
		installMemberName: undefined,
		installMemberId: undefined,
		useStatus: undefined,
		sort: undefined,
		externalLinkId: undefined,
		houseId: undefined,
		houseIdName: undefined,
	})
	const formRules = reactive({
		factoryCode: [
			{
				required: true,
				message: '厂家不能为空',
				trigger: 'blur',
			},
		],
		commId: [
			{
				required: true,
				message: '社区不能为空',
				trigger: 'blur',
			},
		],
		serialServerName: [
			{
				required: true,
				message: '集中器地址不能为空',
				trigger: 'blur',
			},
		],
		serialServerNo: [
			{
				required: true,
				message: '集中器编码不能为空',
				trigger: 'blur',
			},
		],
		installMemberId: [
			{
				required: true,
				message: '安装人员不能为空',
				trigger: 'blur',
			},
		],
		useStatus: [
			{
				required: true,
				message: '电表使用状态不能为空',
				trigger: 'blur',
			},
		],
		sort: [
			{
				required: true,
				message: '序号不能为空',
				trigger: 'blur',
			},
		],
	})
	const formRef = ref() // 表单 Ref
	const communityTree = ref() // 树形结构
	const typeCodes = ref([])
	const products = ref([])

	/** 打开弹窗 */
	const open = async (type: string, id?: number, commId?: number) => {
		dialogVisible.value = true
		dialogTitle.value = t('action.' + type)
		formType.value = type
		resetForm()
		//设置区域默认值
		formData.value.commId = commId
		// 修改时，设置数据
		if (id) {
			formLoading.value = true
			try {
				if (type === 'update') {
					formData.value = await MeterSerialServerApi.getMeterSerialServer(id)
					if (formData.value.houseRoomDO?.id) {
						formData.value.houseId = formData.value.houseRoomDO?.id ?? ''
						formData.value.houseIdName = formData.value.houseRoomDO?.name ?? ''
					} else {
						formData.value.houseId = undefined
						formData.value.houseIdName = undefined
					}

					if (formData.value.factoryCode == '1') {
						getTypeCodes()
						getHxnyProducts()
					} else {
						formData.value.typeCode = undefined
						formData.value.productId = undefined
					}
				}
			} finally {
				formLoading.value = false
			}
		}
		// 获得社区树
		await getTree()
	}
	defineExpose({ open }) // 提供 open 方法，用于打开弹窗

	/** 提交表单 */
	const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
	const submitForm = async () => {
		// 校验表单
		if (!formRef) return
		const valid = await formRef.value.validate()
		if (!valid) return
		// 提交请求
		formLoading.value = true
		try {
			const data = formData.value as unknown as MeterSerialServerApi.MeterSerialServerVo
			if (formType.value === 'create') {
				await MeterSerialServerApi.createMeterSerialServer(data)
				message.success(t('common.createSuccess'))
			} else {
				await MeterSerialServerApi.updateMeterSerialServer(data)
				message.success(t('common.updateSuccess'))
			}
			dialogVisible.value = false
			// 发送操作成功的事件
			emit('success')
		} finally {
			formLoading.value = false
		}
	}

	/** 重置表单 */
	const resetForm = () => {
		formData.value = {
			id: undefined,
			factoryCode: undefined,
			typeCode: undefined,
			productId: undefined,
			commId: undefined,
			serialServerName: undefined,
			serialServerNo: undefined,
			installMemberName: undefined,
			installMemberId: undefined,
			useStatus: undefined,
			sort: undefined,
			externalLinkId: undefined,
			houseId: undefined,
			houseIdName: undefined,
		}
		formRef.value?.resetFields()
	}

	// 选择安装人员
	const openSelectMemberRef = ref()
	const openSelectMember = async () => {
		openSelectMemberRef.value.open()
	}

	const confirmMemberUser = async (memberUser: any) => {
		formData.value.installMemberId = memberUser.id
		formData.value.installMemberName = memberUser.nickname
	}

	const clearSelectMember = async () => {
		formData.value.installMemberId = undefined
		formData.value.installMemberName = undefined
	}

	// 选择安装人员
	const openSelectHouseRef = ref()
	const openSelectHouse = async () => {
		openSelectHouseRef.value.open(formData.value.commId)
	}

	const confirmBuildingAddress = async (buildingAddress: any) => {
		formData.value.houseId = buildingAddress.id
		formData.value.houseIdName = buildingAddress.name
	}

	const clearSelectHouse = async () => {
		formData.value.houseId = undefined
		formData.value.houseIdName = undefined
	}

	/** 获得区域树 */
	const getTree = async () => {
		communityTree.value = []
		const data = await CommunityApi.listSimpleCommunitys()
		let community: Tree = { id: 0, name: '顶级区域', children: [] }
		community.children = handleTree(data)
		communityTree.value.push(community)
	}

	const getTypeCodes = () => {
		typeCodes.value = []
		if (formData.value.factoryCode == '1') {
			typeCodes.value = getStrDictOptions(DICT_TYPE.METER_PRODUCT_TYPE).filter(dict => dict.value == '1007' || dict.value == '1008')
		}
	}

	const getHxnyProducts = async () => {
		const data = await MeterHxnyDictApi.getMeterHxnyDictList(formData.value.typeCode)
		products.value = data
	}
</script>
